package com.netease.financial.base.splash;

import com.google.gson.Gson;
import com.netease.financial.common.util.NfsLog;
import com.netease.financial.domain.interactor.DefaultSubscriber;
import com.netease.financial.domain.interactor.UseCase;
import com.netease.financial.domain.model.LaunchPage;
import com.netease.financial.internal.di.ActivityScope;
import com.netease.financial.mapper.NfsViewModelDataMapper;
import com.netease.financial.module.activitypage.AdvertisementPreferencesHelper;

import javax.inject.Inject;
import javax.inject.Named;

/**
 * Created by hzwuyufeng on 2/15/16.
 */
@ActivityScope
public class SplashPresenterImpl implements SplashPresenter {

    private static final String TAG = SplashPresenterImpl.class.getSimpleName();

    private SplashView splashView;

    private final UseCase getLaunchPage;
    private final NfsViewModelDataMapper nfsViewModelDataMapper;

    @Inject
    public SplashPresenterImpl(@Named("launch_page") UseCase getLaunchPage, NfsViewModelDataMapper nfsViewModelDataMapper) {
        this.getLaunchPage = getLaunchPage;
        this.nfsViewModelDataMapper = nfsViewModelDataMapper;
    }

    @Override
    public void setView(SplashView view) {
        splashView = view;
    }

    @Override
    public void refreshLaunchPage() {
        Gson gson = new Gson();
        LaunchPage launchPage = gson.fromJson(AdvertisementPreferencesHelper.getLaunchPage(), LaunchPage.class);
        if (launchPage != null) {
            splashView.showLaunchPage(nfsViewModelDataMapper.transform(launchPage));
        }
        this.getLaunchPage.execute(new LaunchPageSubscriber());
    }

    @Override
    public void onResume() {

    }

    @Override
    public void onPause() {

    }

    @Override
    public void onDestroy() {
        getLaunchPage.unsubscribe();
    }

    @Override
    public void initialize() {

    }

    private void onLaunchPageInfoReceived(LaunchPage launchPage) {
        Gson gson = new Gson();
        AdvertisementPreferencesHelper.setLaunchPage(gson.toJson(launchPage));
        splashView.showLaunchPage(nfsViewModelDataMapper.transform(launchPage));
    }

    private final class LaunchPageSubscriber extends DefaultSubscriber<LaunchPage> {
        @Override
        public void onCompleted() {
            super.onCompleted();
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
            NfsLog.d(TAG, e.getMessage());
        }

        @Override
        public void onNext(LaunchPage launchPage) {
            super.onNext(launchPage);
            SplashPresenterImpl.this.onLaunchPageInfoReceived(launchPage);
        }
    }
}
